package cn.bctools.mail.config;

import cn.bctools.common.entity.dto.UserDto;
import cn.bctools.common.exception.NotLoginException;
import cn.bctools.mail.entity.JamesUser;
import cn.bctools.mail.service.IJamesUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;


public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    private final IJamesUserService jamesUserService;
    private final JwtUtil jwtUtil;

    public JwtAuthenticationTokenFilter(IJamesUserService jamesUserService, JwtUtil jwtUtil) {
        this.jamesUserService = jamesUserService;
        this.jwtUtil = jwtUtil;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        final String authorizationHeader = request.getHeader("Authorization");

        String username = null;
        String jwt = null;

        // 从请求头中提取Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            jwt = authorizationHeader.substring(7);
            username = jwtUtil.extractUsername(jwt);
            if(username == null) {
                throw new NotLoginException("用户未登录");
            }
        }

        // 验证Token并设置认证信息
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            JamesUser jamesUser = jamesUserService.queryByUserName(username);

            if (jwtUtil.validateToken(jwt, jamesUser)) {
                UserDto dto  = new UserDto();
                dto.setId();
                dto.setRealName();
                dto.setEmail();
                dto.setConfigId();

                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        jamesUser, null, new ArrayList<>());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        filterChain.doFilter(request, response);
    }
}
